package com.qth.valet.common.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qth.valet.common.annotation.Release;
import com.qth.valet.common.exception.NoAuthException;
import com.qth.valet.common.theadlocal.UserOrDriverIdHolder;
import com.qth.valet.common.utils.LoginTypeConstants;
import com.qth.valet.entity.po.Users;
import com.qth.valet.service.UsersService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
@RequiredArgsConstructor
public class AuthorizationInterceptor implements HandlerInterceptor {

    private final UsersService usersService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Release annotation = method.getAnnotation(Release.class);
            if (annotation != null) {
                // 如果加了此注解，放行
                return true;
            } else {
                // 没加注解，需要进行身份校验
                try {
                    StpUtil.checkLogin();
                } catch (Exception e) {
                    throw new NoAuthException();
                }
                String loginDevice = StpUtil.getTokenInfo().getLoginDevice();
                // 判断登陆类型设置ID并放行
                if (LoginTypeConstants.DRIVER.equals(loginDevice)) {
                    Integer driverId = Integer.parseInt((String) StpUtil.getLoginId());
                    UserOrDriverIdHolder.setDriverId(driverId);
                } else {
                    String userOpenId = (String) StpUtil.getLoginId();
                    // 查询用户ID
                    Users one = usersService.getOne(new LambdaQueryWrapper<Users>().eq(Users::getOpenId, userOpenId));
                    if (one == null) {
                        return false;
                    }
                    UserOrDriverIdHolder.setUserId(one.getId());
                }
                return true;
            }
        }
        // 放行请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 清除线程变量
        UserOrDriverIdHolder.clear();
    }
}
